package dx.util;

import org.dx.oho.entity.PersonInfo;
import org.jetbrains.annotations.NotNull;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;

/**
 * create by duanx 2020/12/20
 *@description： 实体和map的转换
 *@classname: ObjMap
 *@author: duanx
 *@date: 2020/12/20 17:13
 **/
public class ObjMapUtil {
    /**
     * 将实体对象转成Map
     * @param obj 实体对象
     * @return map
     * @deprecated Replaced by ObjMap.convertObjToMap(Object obj)
     */
    @NotNull
    public static Map<String, Object> objectToMap(Object obj) {
        Map<String, Object> map = new HashMap<>(32);
        if (obj == null) {
            return map;
        }
        Class<?> clazz = obj.getClass();
        Field[] fields = clazz.getDeclaredFields();
        try {
            for (Field field : fields) {
                field.setAccessible(true);
                map.put(field.getName(), field.get(obj));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return map;
    }


    /**
     * JavaBean对象转属性换为Map包括父对象的属性
     * @param obj 对象
     * @return map
     */
    public static Map<String, Object> convertObjToMap(Object obj){
        Map<String,Object> reMap = new HashMap<>(32);
        if (obj == null) {
            return null;
        }
        try {
            Class<?> objClass = obj.getClass();
            while(objClass != null){
                Field[] fields = objClass.getDeclaredFields();
                for (Field field : fields) {
                    try {
                        Field f = objClass.getDeclaredField(field.getName());
                        f.setAccessible(true);
                        Object o = f.get(obj);
                        reMap.put(field.getName(), o);
                    } catch (NoSuchFieldException | IllegalArgumentException | IllegalAccessException e) {
                        e.printStackTrace();
                    }
                }
                objClass = objClass.getSuperclass();
            }
        } catch (SecurityException e) {
            e.printStackTrace();
        }
        return reMap;
    }
    public static void main(String[] args) {
        PersonInfo personInfo = new PersonInfo();
        personInfo.setUserId(1L);
        Map<String,Object> map = convertObjToMap(personInfo);
        System.out.println(map.toString());
    }
}


